<?php

namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\Exception;

class Sereal
{
    /* @var $httpClient HttpClient */
    private $httpClient;
    private $cacheClass;
    private $client_key = "wmdj";
    private $client_secret = "6lyxudVEPFNpcvsQoiNycajiKKPDS8fk";
    private $client_token = "";

    public function __construct($config = [])
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
//        $this->client_key = $config['client_key'] ?? "awg1hfaffbac94e3";
//        $this->client_secret = $config['client_secret'] ?? "16bb95421d67fdbd4ffef97bcbbbde41";
    }

    public function getHeader()
    {
        $timestamp = time();
        return [
            "Content-Type" => "application/json;charset=UTF-8",
            'timestamp' => $timestamp,
            'authorization' => md5($this->client_key . $this->client_secret . $timestamp),
        ];
    }

    public function createKeyword($code)
    {
        $url = "http://notify-ad.serealplus.com/promotionPassword/partner/$this->client_key/password/create?";
        $body = [
            'code' => $code,
            'num' => 1,
        ];

        $response = $this->httpClient->sendPostRequest($url . http_build_query($body), [], $this->getHeader());

        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['code']) && $result['code'] == 200) {
            return $result['data'][0]['contentPassword'];
        } else {
            throw new Exception(9999, $result['msg'] ?? "系统错误");
        }

        return false;

    }

    public function getKeywordOrder($password, $startDate, $endDate)
    {
        $url = "http://notify-ad.serealplus.com/promotionPassword/partner/{$this->client_key}/password/report?";
        $body = [
            'password' => $password,
            'startDate' => $startDate,
            'endDate' => $endDate,
        ];

        $url = $url. http_build_query($body);
        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['code']) && $result['code'] == 200) {
            return $result['data'];
        }

        return [];
    }
    public function getVideo($page, $size)
    {
        $url = "http://notify-ad.serealplus.com/promotionPassword/partner/{$this->client_key}/content/list?";

        $body = [
            'page' => $page,
            'size' => $size,
        ];

        $url = $url. http_build_query($body);
        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['code']) && $result['code'] == 200) {
            return $result['data']['records'];
        }

        return [];
    }
}